package thread;

import com.sun.org.apache.xpath.internal.operations.String;

/**
 * StringBuilder和StringBuffer
 * StringBuilder不是并发安全，StringBuffer是线性安全的
 *
 * StringBuilder的结果，两个thread1都抢着往里边拼接字符串，会出现各种错误
 * StringBuffer的源代码里，该类型是被synchronized修饰的，所以是同步执行的，不会出现并发安全问题
 */
public class SyncDemo4 {
    public static void main(String[] args) {
//        StringBuilder sb = new StringBuilder();
        StringBuffer sb = new StringBuffer();
        Thread thread1 = new Thread(){
            public void run(){
                for (int i = 0; i < 1000; i++) {
                    sb.append("abc");
                }
            }
        };
        Thread thread2=new Thread(){
            public void run(){
                for (int i = 0; i < 1000; i++) {
                    sb.append("def");
                }
            }
        };
        thread1.start();
        thread2.start();

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(sb.length());
        System.out.println(sb);
    }
}
